package com.mxun.winefox

import android.Manifest
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.mxun.winefox.components.ChatHistory
import com.mxun.winefox.components.InputBar
import com.mxun.winefox.components.SettingsDrawer
import com.mxun.winefox.data.ChatMessage
import kotlinx.coroutines.launch

@Composable
fun MainScreen(viewModel: MainViewModel) {
    val context = LocalContext.current
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    var showClearConfirmation by remember { mutableStateOf(false) }

    // 状态
    val chatHistory = viewModel.chatHistory
    val inputText by viewModel.inputText
    val isTTSPlaying by viewModel.isTTSPlaying
    val playingMessage by viewModel.playingMessage
    val isRecording by viewModel.voiceRecognizer.isRecording

    // 设置状态
    val persona by viewModel.persona
    val isActiveChatEnabled by viewModel.isActiveChatEnabled
    val isTTSEnabled by viewModel.isTTSEnabled
    val voiceModelId by viewModel.voiceModelId
    val isBilingualDisplay by viewModel.isShowBilingual


    // 权限请求
    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (granted) {
            viewModel.startListening()
        } else {
            Toast.makeText(context, "主人不给权限的话,酒狐没法听到主人说话哦~", Toast.LENGTH_SHORT).show()
        }
    }

    // 清除确认对话框
    if (showClearConfirmation) {
        AlertDialog(
            onDismissRequest = { showClearConfirmation = false },
            title = { Text("清除聊天记录") },
            text = { Text("确定要清除所有聊天记录吗？此操作不可恢复。") },
            confirmButton = {
                Button(onClick = {
                    viewModel.clearChatHistory()
                    showClearConfirmation = false
                }) { Text("确定清除") }
            },
            dismissButton = {
                TextButton(onClick = { showClearConfirmation = false }) {
                    Text("取消")
                }
            }
        )
    }

    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            SettingsDrawer(
                persona = persona,
                onPersonaChange = { viewModel.persona.value = it },
                isTTSEnabled = isTTSEnabled,
                onTTSEnabledChange = { viewModel.isTTSEnabled.value = it },
                isActiveChatEnabled = isActiveChatEnabled,
                onActiveChatEnabledChange = { viewModel.isActiveChatEnabled.value = it },
                voiceModels = viewModel.voiceModels,
                selectedVoiceId = voiceModelId,
                onVoiceModelSelected = { viewModel.voiceModelId.value = it },
                onClearChatHistory = { showClearConfirmation = true },
                onCloseDrawer = { scope.launch { drawerState.close() } },
                modifier = Modifier.fillMaxHeight(),
                isBilingualDisplay = isBilingualDisplay,
                onBilingualDisplayChange = { viewModel.toggleBilingualDisplay() },

                )
        }
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.1f),
                            MaterialTheme.colorScheme.background
                        )
                    )
                )
        ) {
            BackgroundImage()

            Scaffold(
                topBar = {
                    FixedTopAppBar(
                        isThinking = viewModel.isThinking.value,
                        onSettingsClick = {
                            scope.launch {
                                if (drawerState.isClosed) drawerState.open()
                                else drawerState.close()
                            }
                        }
                    )
                },
                containerColor = Color.Transparent
            ) { innerPadding ->
                ChatLayout(
                    chatHistory = chatHistory,
                    playingMessage = playingMessage,
                    isTTSPlaying = isTTSPlaying,
                    inputText = inputText,
                    isRecording = isRecording,
                    onInputTextChange = { viewModel.inputText.value = it },
                    onSendClick = viewModel::sendMessage,
                    onVoiceClick = {
                        if (isRecording) {
                            viewModel.stopListening()
                        } else {
                            permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
                        }
                    },
                    onPlayMessage = viewModel::playMessage,
                    onRefreshMessage = viewModel::refreshAudioCache,
                    modifier = Modifier.padding(innerPadding),
                    isBilingualDisplay = isBilingualDisplay,
                    cachedMessages = viewModel.cachedMessages,
                    isJapaneseVoice = viewModel.isJapaneseVoice
                )

            }
        }
    }
}

@Composable
private fun BackgroundImage() {
    Image(
        painter = painterResource(id = R.drawable.winefox),
        contentDescription = "背景立绘",
        contentScale = ContentScale.Crop,
        modifier = Modifier
            .fillMaxSize()
            .alpha(0.8f)
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FixedTopAppBar(isThinking: Boolean, onSettingsClick: () -> Unit) {
    CenterAlignedTopAppBar(
        title = {
            Text(
                if (isThinking) "酒狐思考中~" else "酒 狐",
                style = MaterialTheme.typography.titleLarge.copy(
                    fontWeight = FontWeight.Bold

                )
            )
        },
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f)
        ),
        actions = {
            IconButton(
                onClick = onSettingsClick,
                modifier = Modifier
                    .padding(end = 8.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.secondaryContainer)
            ) {
                Icon(
                    Icons.Default.Settings,
                    contentDescription = "设置",
                    tint = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }
    )
}


@Composable
private fun ChatLayout(
    chatHistory: List<ChatMessage>,
    playingMessage: String?,
    isTTSPlaying: Boolean,
    inputText: String,
    isRecording: Boolean,
    onInputTextChange: (String) -> Unit,
    onSendClick: () -> Unit,
    onVoiceClick: () -> Unit,
    onPlayMessage: (ChatMessage) -> Unit,
    onRefreshMessage: (ChatMessage) -> Unit,
    modifier: Modifier = Modifier,
    isBilingualDisplay: Boolean,
    cachedMessages: Set<String>,
    isJapaneseVoice: Boolean
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
    ) {
        ChatHistory(
            chatHistory = chatHistory,
            playingMessage = playingMessage,
            isTTSPlaying = isTTSPlaying,
            onPlayMessage = onPlayMessage,
            onRefreshMessage = onRefreshMessage,
            modifier = Modifier.weight(1f),
            isBilingualDisplay = isBilingualDisplay,
            cachedMessages = cachedMessages,
            isJapaneseVoice = isJapaneseVoice
        )

        Spacer(modifier = Modifier.height(16.dp))

        InputBar(
            inputText = inputText,
            onInputTextChange = onInputTextChange,
            isRecording = isRecording,
            isTTSPlaying = isTTSPlaying,
            hasCachedAudio = cachedMessages.contains(inputText),
            onSendClick = onSendClick,
            onVoiceClick = onVoiceClick
        )
    }
}